﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Caching;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Net.Http;
using ShopDal.Models;

namespace NT40Redis.Controllers
{
    public class ProductController : Controller
    {
        RedisCache redis;
        IConfiguration config;
        public ProductController(IConfiguration configuration, RedisCache cache) { 
            redis = cache;
            config = configuration;        
        }
        public async Task<IActionResult> Index()
        {
            //从缓存读取数据
            string prodJson = redis.GetString("prods");
            if (string.IsNullOrEmpty(prodJson))
            {
                //缓存没有则通过api读数据库
                HttpClient httpClient = new HttpClient();
                prodJson = await httpClient.GetStringAsync(config.GetSection("APIUrl").Value);
                //数据保存到缓存
                redis.SetString("prods", prodJson);
            }
            //将json格式的数据反系列化啊
            IEnumerable<Products> prodList = JsonConvert.DeserializeObject<IEnumerable<Products>>(prodJson);
            return View(prodList);
        }
    }
}